package com.gxc.healthfood.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxc.healthfood.entity.Foods;
import com.gxc.healthfood.mapper.FoodsMapper;
import com.gxc.healthfood.service.FoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 食物服务实现类
 * @author zhouxin
 * @since 2024-05-16
 */
@Service
public class FoodsServiceImpl extends ServiceImpl<FoodsMapper, Foods> implements FoodsService {

    @Autowired
    private FoodsMapper foodsMapper;

    /**
     * 根据名称查找食物
     * @param name 食物名称
     * @return 食物实体
     */
    @Override
    public Foods findByName(String name) {
        QueryWrapper<Foods> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", name);
        return getOne(queryWrapper);
    }

    /**
     * 分页查询食物列表（包含营养成分）
     * @param page 页码
     * @param pageSize 每页数量
     * @param conditions 查询条件
     * @return 食物列表
     */
    @Override
    public List<Map<String, Object>> findFoodsWithNutrients(Integer page, Integer pageSize, Map<String, Object> conditions) {
        // 计算偏移量
        int offset = (page - 1) * pageSize;
        
        // 构建查询条件
        Map<String, Object> params = new HashMap<>(conditions);
        params.put("offset", offset);
        params.put("pageSize", pageSize);
        
        return foodsMapper.selectFoodsWithNutrients(params);
    }

    /**
     * 根据条件查询食物总数
     * @param conditions 查询条件
     * @return 食物总数
     */
    @Override
    public long countFoodsWithConditions(Map<String, Object> conditions) {
        QueryWrapper<Foods> queryWrapper = new QueryWrapper<>();
        
        // 添加搜索关键词条件
        if (conditions.containsKey("keyword")) {
            String keyword = (String) conditions.get("keyword");
            queryWrapper.like("name", keyword).or().like("description", keyword);
        }
        
        // 添加分类ID条件
        if (conditions.containsKey("categoryId")) {
            Integer categoryId = (Integer) conditions.get("categoryId");
            queryWrapper.eq("category_id", categoryId);
        }
        
        return count(queryWrapper);
    }
}




